package web.controller;

import common.Const;
import service.BookInfoService;
import service.impl.BookInfoServiceImpl;
import util.PageHelper;
import util.StrUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * User: key
 * ClassName:BookController
 * Date: 2023/5/6
 * Time: 16:02
 * description:
 */
@WebServlet("/book")
public class BookController extends HttpServlet {
    private BookInfoService bs = new BookInfoServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method == null) {
            method = "error";
        }
        switch (method){
            case "getByPage":
                getByPage(req,resp);
                break;
            case "borrow":
                borrow(req,resp);
                break;
            case "error":
            default:
                req.setAttribute(Const.MSG,"抱歉，你访问的资源不存在");
                req.getRequestDispatcher("message.jsp").forward(req,resp);
        }
    }

    private void borrow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int bookId = StrUtils.strToInteger(req.getParameter("bookId"));
        String message = bs.borrow(bookId);
        req.setAttribute(Const.MSG,message);
        req.getRequestDispatcher("message.jsp").forward(req,resp);
    }

    private void getByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pageNum = StrUtils.strToInteger(req.getParameter("pageNum"));
        String bookType = req.getParameter("bookType");
        String bookName = req.getParameter("bookName");
        String isBorrow = req.getParameter("isBorrow");
        req.setAttribute("bookType",bookType);
        req.setAttribute("bookName",bookName);
        req.setAttribute("isBorrow",isBorrow);
        //设置一页的数据条数
        int pageSize = 5;
        //通过关键词获取页面相关信息对象
        PageHelper helper = bs.getByPageWithKeyWord(pageNum,pageSize,bookType,bookName,isBorrow);
        req.setAttribute("helper",helper);
        req.getRequestDispatcher("index.jsp").forward(req,resp);
    }
}
